package com.ruiysoft.crm.controller;


import cn.taroco.common.vo.UserVO;
import com.ruiysoft.crm.model.ApiResponseEx;
import com.ruiysoft.crm.model.entity.BizCallLog;
import com.ruiysoft.crm.model.entity.SysUser;
import com.ruiysoft.crm.model.vo.FanRuanCallTimeLogVo;
import com.ruiysoft.crm.service.IBizCallLogService;
import com.ruiysoft.crm.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.time.DateUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 呼叫中心 前端控制器
 * </p>
 *
 * @author 魏雪刚
 * @since 2019-03-23
 */
@RestController
@RequestMapping("/callCenter")
@Api(tags = "callCenter", description = "呼叫中心模块")
public class BizCallCenterController {

    @Autowired
    IBizCallLogService callLogService;
    @Autowired
    SysUserService sysUserService;

//    @Value("${fanruan.ip}")
//    private String fanruanIP;

    ApiResponseEx apiResponseEx = new ApiResponseEx();

    @ApiOperation(value = "插入呼叫记录", notes = "插入呼叫记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "callLog", value = "呼叫记录", dataType = "BizCallLog"),
    })
    @PostMapping("/insert")
    public ApiResponseEx insertCalLog(@RequestBody BizCallLog callLog) {
        return callLogService.insertCallLog(callLog);
    }

    @ApiOperation(value = "获取呼叫记录信息", notes = "获取呼叫记录信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "第几页", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "Integer"),
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer"),
            @ApiImplicitParam(name = "phoneNo", required = false, value = "客户电话号", dataType = "String"),
    })
    @GetMapping("/get")
    public ApiResponseEx getCallLogs(@RequestParam Map<String, Object> params,UserVO userVO) throws Exception {
        int userId=sysUserService.getUserIdByUserName(userVO.getUsername());
        apiResponseEx.setData(callLogService.getCallLogs(params,userId));
        return apiResponseEx;
    }


    @ApiOperation(value = "更新通话记录信息", notes = "更新通话记录信息")
    @ApiImplicitParam(name = "callLog", value = "通话记录", required = true, dataType = "BizCallLog")
    @PutMapping("/update")
    public ApiResponseEx updateCallLog(@RequestBody BizCallLog callLog) throws Exception {
        apiResponseEx.setData(callLogService.updateCallLog(callLog));
        return apiResponseEx;
    }

    @ApiOperation(value = "删除通话记录信息", notes = "删除通话记录信息")
    @ApiImplicitParam(name = "id", value = "通话记录Id", required = true, dataType = "int")
    @DeleteMapping("/delete/{id}")
    public ApiResponseEx deleteCallLog(@PathVariable("id") int id) {
        apiResponseEx = callLogService.deleteCallLog(id);

        return apiResponseEx;
    }

    @ApiOperation(value = "查询通时记录", notes = "查询通时记录")
    @ApiImplicitParam(name = "id", value = "userID", required = true, dataType = "int")
    @GetMapping("/talkTimeLogByUserId")
    public ApiResponseEx talkTimeLogByUserId(@RequestParam("") int userId) {
        apiResponseEx = callLogService.talkTimeLogByUserId(userId);
        return apiResponseEx;
    }

    @GetMapping("/call")
    public ApiResponseEx call(Integer clientId, Integer userId, Integer tag) {
        return callLogService.call(clientId, userId, tag);
    }


    @PostMapping("/callback")
    public ApiResponseEx callback(String uuid, String cdr) {
        Map map = xml2Map(cdr);
        return new ApiResponseEx<String>();
    }

    private static Map<String, String> xml2Map(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            //将xml转为dom对象
            Document doc = DocumentHelper.parseText(xml);
            //获取根节点
            Element root = doc.getRootElement();
            //获取名称为queryRequest的子节点
            Element element = root.element("variables");
            //获取这个子节点里面的所有子元素，
            List<Element> elements = element.elements();
            //遍历子元素
            for (Object obj : elements) {
                element = (Element) obj;
                map.put(element.getName(), element.getTextTrim());
                System.out.println(element.getName() + "--" + element.getTextTrim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 打开通话记录
     *
     * @return 通话记录
     */
    @ApiOperation(value = "查询通时记录", notes = "查询通时记录")
    @GetMapping("/callTimeLog")
    public ApiResponseEx callTimeLog(UserVO userVO,String reportlet) {
        FanRuanCallTimeLogVo logVo = new FanRuanCallTimeLogVo();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        switch (reportlet){
            case "callTimeLog":
                List<SysUser> users = callLogService.callTimeLog(userVO);
                StringBuilder createIds = new StringBuilder();
                for (int i = 0; users != null && i < users.size(); i++) {
                    if (i == 0) {
                        createIds.append("'").append(users.get(0).getUserId()).append("'");
                    } else {
                        createIds.append(",'").append(users.get(i).getUserId()).append("'");
                    }
            /*int userId = users.get(i).getUserId();
            if (i > 0) {
                createIds.append(",");
            }
            createIds.append(userId);*/
                }
//                logVo.setCreateId(createIds.toString());
//                logVo.setAmEnd("13:29");
//                logVo.setPmStart("13:30");
//                logVo.setCurrentDate("2019-05-23");
                String start=sdf.format(new Date())+" 00:00:00";
                String midle=sdf.format(new Date())+" 13:00:00";
                String end=sdf.format(new Date())+" 23:59:59";
                logVo.setUrl("http://39.107.237.7:9031/WebReport/ReportServer?reportlet=callTimeLog.cpt&createId="+createIds.toString()+"&middleDate="+midle+"&endDate="+end+"&startDate="+start);
            case "performanceanagement":
                logVo.setUrl("http://39.107.237.7:9031/WebReport/ReportServer?reportlet="+reportlet+".cpt&date="+sdf.format(new Date()));
            default:

                logVo.setUrl("http://39.107.237.7:9031/WebReport/ReportServer?reportlet="+reportlet+".cpt");
        }


        return ApiResponseEx.with(logVo, 200);
    }

}
